package org.example.asm;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

/**
 * 使用静态方法解决本地变量表的问题
 */
public class MyClassVistor2 extends ClassVisitor {

    public MyClassVistor2(ClassVisitor classVisitor) {
        super(Opcodes.ASM7,classVisitor);
    }

    @Override
    public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        cv.visit(version, access, name, signature, superName, interfaces);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        MethodVisitor mv = cv.visitMethod(access, name, descriptor, signature, exceptions);
        if(!"<init>".equals(name) && mv != null){
            // 为这样的方法增加方法记录时间
            mv = new MyMethodVisitor(mv);
        }
        return mv;
    }
    class MyMethodVisitor extends MethodVisitor{

        public MyMethodVisitor( MethodVisitor mv) {
            super(Opcodes.ASM7, mv);
        }

        /**
         * 开头
         */
        @Override
        public void visitCode() {
            mv.visitCode();

            mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/example/asm/TimeUtil", "start", "()V", false);

        }

        /**
         * 结尾
         * @param opcode
         */
        @Override
        public void visitInsn(int opcode) {

            if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN)
                    || opcode == Opcodes.ATHROW){
                mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/example/asm/TimeUtil", "end", "()V", false);
            }

            mv.visitInsn(opcode);
        }
    }
}
